<?php

class Sql extends ExportConverter {
	private static function escape($value){
		return str_replace(
			array("'","\\"),
			array("\\'","\\\\"),
			$value);
	}
	public function Export(){
		if ( is_null($this->value) )
			return 'NULL';
		if ( is_string($this->value) )
				return "'".self::escape($this->value)."'";
		if ( is_bool($this->value) )
			return $this->value ? '1' : '0';
		if ( is_int($this->value) )
			return sprintf('%d',$this->value);
		if ( is_float($this->value) )
			return sprintf('%F',$this->value);
		if ( $this->value instanceof ID )
			return strval( $this->value->AsInt() );
		if ( $this->value instanceof ImmutableTimeSpan )
			return strval($this->value->GetTotalSeconds());
		if ( $this->value instanceof ImmutableDateTime )
			return "'" . $this->value->Format('Y-m-d H:i:s') . "'";
		if ( $this->value instanceof DateTime )
			return "'" . $this->value->format('Y-m-d H:i:s') . "'";
		if ( $this->value instanceof Lemma )
			return "'".self::escape($this->value->Encode())."'";
		if ($this->value instanceof DBItem)
			return strval( $this->value->id->AsInt() );
		if ($this->value instanceof DBList){
			$r = '';
			foreach ($this->value->ToIDList() as $id) { if ($r!='') $r .= ','; $r .= strval( $id->AsInt() ); }
			return $r=='' ? '(-11111111)' : '('.$r.')';
		}
		if (is_array( $this->value )){
			$r = '';
			foreach ($this->value as $s) { if ($r!='') $r .= ','; $r .= new Sql($s); }
			return $r=='' ? '(-11111111)' : '('.$r.')';
		}
		return "'".self::escape(strval($this->value))."'";
	}



	const ID = 'INT';
	const Integer = 'INT';
	const Boolean = 'TINYINT';
	const DateTime = 'DATETIME';
	const Time = 'DATETIME';
	const TimeSpan = 'INT';
	const String20 = 'VARCHAR(20)';
	const String100 = 'VARCHAR(100)';
	const String255 = 'VARCHAR(255)';
	const Text = 'TEXT';
}



?>